using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.IO;
using Microsoft.Win32;
using MultiTCPProxy.Models;
using MultiTCPProxy.Services;

namespace MultiTCPProxy
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private readonly ProxyManager _proxyManager;
        private readonly ProcessGuardian _processGuardian;
        private ProxyConfig _selectedProxy;

        public MainWindow()
        {
            try
            {
                DebugLogger.Log("正在初始化主窗口");
                InitializeComponent();

                _proxyManager = ProxyManager.Instance;
                _processGuardian = ProcessGuardian.Instance;
                dgProxies.ItemsSource = _proxyManager.ProxyConfigs;

                // 注册事件处理
                _proxyManager.ConnectionEstablished += ProxyManager_ConnectionEstablished;
                _proxyManager.ConnectionClosed += ProxyManager_ConnectionClosed;
                _proxyManager.DataTransferred += ProxyManager_DataTransferred;

                // 启动进程守护
                _processGuardian.StartMonitoring();
                DebugLogger.Log("主窗口初始化完成");

                // 检查服务状态
                UpdateServiceStatus();
            }
            catch (Exception ex)
            {
                DebugLogger.LogException(ex, "主窗口初始化失败");
                MessageBox.Show($"程序初始化失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                Application.Current.Shutdown();
            }
        }

        private void UpdateServiceStatus()
        {
            bool isInstalled = WindowsServiceManager.IsServiceInstalled();
            bool isRunning = isInstalled && WindowsServiceManager.IsServiceRunning();

            btnInstallService.IsEnabled = !isInstalled;
            btnUninstallService.IsEnabled = isInstalled && !isRunning;
            btnStartService.IsEnabled = isInstalled && !isRunning;
            btnStopService.IsEnabled = isRunning;

            lblServiceStatus.Content = isInstalled ? 
                (isRunning ? "服务状态: 已安装且正在运行" : "服务状态: 已安装但未运行") : 
                "服务状态: 未安装";
        }

        private void ProxyManager_ConnectionEstablished(object sender, ProxyEventArgs e)
        {
            Dispatcher.Invoke(() =>
            {
                AddLogMessage($"[{e.Config.Name}] 新连接建立: {e.Connection.ClientEndPoint}");
            });
        }

        private void ProxyManager_ConnectionClosed(object sender, ProxyEventArgs e)
        {
            Dispatcher.Invoke(() =>
            {
                AddLogMessage($"[{e.Config.Name}] 连接关闭: {e.Connection.ClientEndPoint}");
            });
        }

        private void ProxyManager_DataTransferred(object sender, ProxyDataEventArgs e)
        {
            // 数据传输事件较频繁，可以选择不记录日志或者只记录重要数据
            // 这里更新UI上的统计信息
            Dispatcher.Invoke(() =>
            {
                // 刷新数据网格以显示更新的统计信息
                dgProxies.Items.Refresh();
            });
        }

        private void AddLogMessage(string message)
        {
            txtLog.AppendText($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] {message}\r\n");
            txtLog.ScrollToEnd();
        }

        private void BtnAddProxy_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 验证输入
                if (string.IsNullOrWhiteSpace(txtName.Text))
                {
                    MessageBox.Show("请输入代理名称", "输入错误", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                if (!int.TryParse(txtListenPort.Text, out int listenPort) || listenPort <= 0 || listenPort > 65535)
                {
                    MessageBox.Show("请输入有效的监听端口(1-65535)", "输入错误", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                if (string.IsNullOrWhiteSpace(txtTargetIP.Text))
                {
                    MessageBox.Show("请输入目标服务器IP", "输入错误", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                if (!int.TryParse(txtTargetPort.Text, out int targetPort) || targetPort <= 0 || targetPort > 65535)
                {
                    MessageBox.Show("请输入有效的目标端口(1-65535)", "输入错误", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                // 创建新的代理配置
                var config = new ProxyConfig
                {
                    Name = txtName.Text,
                    ListenPort = listenPort,
                    TargetIP = txtTargetIP.Text,
                    TargetPort = targetPort,
                    IsEnabled = false
                };

                // 添加到管理器
                _proxyManager.AddProxy(config);
                ClearInputFields();
                AddLogMessage($"添加代理配置: {config.Name}");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"添加代理失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void BtnUpdateProxy_Click(object sender, RoutedEventArgs e)
        {
            if (_selectedProxy == null)
            {
                MessageBox.Show("请先选择要更新的代理配置", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            try
            {
                // 验证输入
                if (!int.TryParse(txtListenPort.Text, out int listenPort) || listenPort <= 0 || listenPort > 65535)
                {
                    MessageBox.Show("请输入有效的监听端口(1-65535)", "输入错误", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                if (string.IsNullOrWhiteSpace(txtTargetIP.Text))
                {
                    MessageBox.Show("请输入目标服务器IP", "输入错误", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                if (!int.TryParse(txtTargetPort.Text, out int targetPort) || targetPort <= 0 || targetPort > 65535)
                {
                    MessageBox.Show("请输入有效的目标端口(1-65535)", "输入错误", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                // 更新配置
                var config = new ProxyConfig
                {
                    Name = _selectedProxy.Name,
                    ListenPort = listenPort,
                    TargetIP = txtTargetIP.Text,
                    TargetPort = targetPort
                };

                _proxyManager.UpdateProxy(config);
                ClearInputFields();
                _selectedProxy = null;
                btnAddProxy.IsEnabled = true;
                btnUpdateProxy.IsEnabled = false;
                txtName.IsEnabled = true;
                AddLogMessage($"更新代理配置: {config.Name}");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"更新代理失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void BtnDeleteProxy_Click(object sender, RoutedEventArgs e)
        {
            var proxy = ((Button)sender).DataContext as ProxyConfig;
            if (proxy == null) return;

            var result = MessageBox.Show($"确定要删除代理 '{proxy.Name}' 吗？", "确认删除", MessageBoxButton.YesNo, MessageBoxImage.Question);
            if (result == MessageBoxResult.Yes)
            {
                try
                {
                    _proxyManager.RemoveProxy(proxy.Name);
                    AddLogMessage($"删除代理配置: {proxy.Name}");

                    // 如果正在编辑这个代理，清除编辑状态
                    if (_selectedProxy != null && _selectedProxy.Name == proxy.Name)
                    {
                        ClearInputFields();
                        _selectedProxy = null;
                        btnAddProxy.IsEnabled = true;
                        btnUpdateProxy.IsEnabled = false;
                        txtName.IsEnabled = true;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"删除代理失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }

        private void BtnStartProxy_Click(object sender, RoutedEventArgs e)
        {
            var proxy = ((Button)sender).DataContext as ProxyConfig;
            if (proxy == null) return;

            try
            {
                _proxyManager.StartProxy(proxy.Name);
                AddLogMessage($"启动代理: {proxy.Name}");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"启动代理失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void BtnStopProxy_Click(object sender, RoutedEventArgs e)
        {
            var proxy = ((Button)sender).DataContext as ProxyConfig;
            if (proxy == null) return;

            try
            {
                _proxyManager.StopProxy(proxy.Name);
                AddLogMessage($"停止代理: {proxy.Name}");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"停止代理失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void BtnEditProxy_Click(object sender, RoutedEventArgs e)
        {
            var proxy = ((Button)sender).DataContext as ProxyConfig;
            if (proxy == null) return;

            _selectedProxy = proxy;
            txtName.Text = proxy.Name;
            txtListenPort.Text = proxy.ListenPort.ToString();
            txtTargetIP.Text = proxy.TargetIP;
            txtTargetPort.Text = proxy.TargetPort.ToString();

            txtName.IsEnabled = false; // 不允许修改名称
            btnAddProxy.IsEnabled = false;
            btnUpdateProxy.IsEnabled = true;
        }

        private void ClearInputFields()
        {
            txtName.Text = string.Empty;
            txtListenPort.Text = string.Empty;
            txtTargetIP.Text = string.Empty;
            txtTargetPort.Text = string.Empty;
        }

        private void BtnInstallService_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                DebugLogger.Log("正在安装Windows服务");
                if (WindowsServiceManager.InstallService())
                {
                    MessageBox.Show("服务安装成功！", "成功", MessageBoxButton.OK, MessageBoxImage.Information);
                    DebugLogger.Log("Windows服务安装成功");
                    UpdateServiceStatus();
                }
                else
                {
                    MessageBox.Show("服务安装失败！", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    DebugLogger.Log("Windows服务安装失败", LogLevel.Error);
                }
            }
            catch (Exception ex)
            {
                DebugLogger.LogException(ex, "安装服务时发生错误");
                MessageBox.Show($"安装服务时发生错误: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void BtnUninstallService_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                DebugLogger.Log("正在卸载Windows服务");
                if (WindowsServiceManager.UninstallService())
                {
                    MessageBox.Show("服务卸载成功！", "成功", MessageBoxButton.OK, MessageBoxImage.Information);
                    DebugLogger.Log("Windows服务卸载成功");
                    UpdateServiceStatus();
                }
                else
                {
                    MessageBox.Show("服务卸载失败！", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    DebugLogger.Log("Windows服务卸载失败", LogLevel.Error);
                }
            }
            catch (Exception ex)
            {
                DebugLogger.LogException(ex, "卸载服务时发生错误");
                MessageBox.Show($"卸载服务时发生错误: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void BtnStartService_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                DebugLogger.Log("正在启动Windows服务");
                if (WindowsServiceManager.StartService())
                {
                    MessageBox.Show("服务启动成功！", "成功", MessageBoxButton.OK, MessageBoxImage.Information);
                    DebugLogger.Log("Windows服务启动成功");
                    UpdateServiceStatus();
                }
                else
                {
                    MessageBox.Show("服务启动失败！", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    DebugLogger.Log("Windows服务启动失败", LogLevel.Error);
                }
            }
            catch (Exception ex)
            {
                DebugLogger.LogException(ex, "启动服务时发生错误");
                MessageBox.Show($"启动服务时发生错误: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void BtnStopService_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                DebugLogger.Log("正在停止Windows服务");
                if (WindowsServiceManager.StopService())
                {
                    MessageBox.Show("服务停止成功！", "成功", MessageBoxButton.OK, MessageBoxImage.Information);
                    DebugLogger.Log("Windows服务停止成功");
                    UpdateServiceStatus();
                }
                else
                {
                    MessageBox.Show("服务停止失败！", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    DebugLogger.Log("Windows服务停止失败", LogLevel.Error);
                }
            }
            catch (Exception ex)
            {
                DebugLogger.LogException(ex, "停止服务时发生错误");
                MessageBox.Show($"停止服务时发生错误: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void MenuExit_Click(object sender, RoutedEventArgs e)
        {
            DebugLogger.Log("用户点击退出菜单");
            Close();
        }

        private void MenuInstallService_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                DebugLogger.Log("正在安装Windows服务");
                if (WindowsServiceManager.InstallService())
                {
                    MessageBox.Show("服务安装成功！", "成功", MessageBoxButton.OK, MessageBoxImage.Information);
                    DebugLogger.Log("Windows服务安装成功");
                }
                else
                {
                    MessageBox.Show("服务安装失败！", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    DebugLogger.Log("Windows服务安装失败", LogLevel.Error);
                }
            }
            catch (Exception ex)
            {
                DebugLogger.LogException(ex, "安装服务时发生错误");
                MessageBox.Show($"安装服务时发生错误: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void Window_Closing(object sender, CancelEventArgs e)
        {
            try
            {
                DebugLogger.Log("正在关闭主窗口");
                // 停止进程守护
                _processGuardian.StopMonitoring();

                // 停止所有代理
                _proxyManager.StopAllProxies();
                DebugLogger.Log("主窗口关闭完成");
            }
            catch (Exception ex)
            {
                DebugLogger.LogException(ex, "关闭主窗口时发生错误");
            }
        }

        // 菜单事件补全
        private void MenuUninstallService_Click(object sender, RoutedEventArgs e)
        {
            var win = new ServiceManagerWindow();
            win.Owner = this;
            win.ShowDialog();
        }
        private void MenuStartService_Click(object sender, RoutedEventArgs e)
        {
            var win = new ServiceManagerWindow();
            win.Owner = this;
            win.ShowDialog();
        }
        private void MenuStopService_Click(object sender, RoutedEventArgs e)
        {
            var win = new ServiceManagerWindow();
            win.Owner = this;
            win.ShowDialog();
        }
        private void MenuAddProxy_Click(object sender, RoutedEventArgs e)
        {
            var win = new ProxyEditWindow();
            win.Owner = this;
            if (win.ShowDialog() == true)
            {
                // 这里可以添加代理逻辑
                // 例如：_proxyManager.AddProxy(...)
            }
        }
        private void MenuEditProxy_Click(object sender, RoutedEventArgs e)
        {
            if (dgProxies.SelectedItem is ProxyConfig proxy)
            {
                var win = new ProxyEditWindow();
                win.Owner = this;
                // 可预填数据
                win.txtName.Text = proxy.Name;
                win.txtListenPort.Text = proxy.ListenPort.ToString();
                win.txtTargetIP.Text = proxy.TargetIP;
                win.txtTargetPort.Text = proxy.TargetPort.ToString();
                if (win.ShowDialog() == true)
                {
                    // 这里可以更新代理逻辑
                }
            }
            else
            {
                MessageBox.Show("请先选择要编辑的代理", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }
        private void MenuDeleteProxy_Click(object sender, RoutedEventArgs e)
        {
            if (dgProxies.SelectedItem is ProxyConfig proxy)
            {
                var result = MessageBox.Show($"确定要删除代理 '{proxy.Name}' 吗？", "确认删除", MessageBoxButton.YesNo, MessageBoxImage.Question);
                if (result == MessageBoxResult.Yes)
                {
                    _proxyManager.RemoveProxy(proxy.Name);
                }
            }
            else
            {
                MessageBox.Show("请先选择要删除的代理", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }
        private void MenuAbout_Click(object sender, RoutedEventArgs e)
        {
            var win = new AboutWindow();
            win.Owner = this;
            win.ShowDialog();
        }

        private void MenuExportConfig_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var saveFileDialog = new SaveFileDialog
                {
                    Filter = "JSON文件|*.json",
                    Title = "导出代理配置",
                    DefaultExt = "json",
                    FileName = $"代理配置_{DateTime.Now:yyyyMMdd_HHmmss}.json"
                };

                if (saveFileDialog.ShowDialog() == true)
                {
                    var configs = new List<ProxyConfig>();
                    foreach (var item in dgProxies.Items)
                    {
                        if (item is ProxyConfig config)
                        {
                            configs.Add(new ProxyConfig
                            {
                                Name = config.Name,
                                ListenPort = config.ListenPort,
                                TargetIP = config.TargetIP,
                                TargetPort = config.TargetPort,
                                Enabled = config.IsEnabled,
                                Description = config.Description
                            });
                        }
                    }

                    string json = ProxyConfig.Serialize(configs);
                    File.WriteAllText(saveFileDialog.FileName, json);
                    MessageBox.Show("配置导出成功！", "成功", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"导出配置失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void MenuImportConfig_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var openFileDialog = new OpenFileDialog
                {
                    Filter = "JSON文件|*.json",
                    Title = "导入代理配置"
                };

                if (openFileDialog.ShowDialog() == true)
                {
                    string json = File.ReadAllText(openFileDialog.FileName);
                    var configs = ProxyConfig.Deserialize(json);

                    if (configs != null && configs.Count > 0)
                    {
                        var result = MessageBox.Show(
                            $"是否导入 {configs.Count} 个代理配置？\n注意：这将覆盖现有的配置。",
                            "确认导入",
                            MessageBoxButton.YesNo,
                            MessageBoxImage.Question);

                        if (result == MessageBoxResult.Yes)
                        {
                            // 停止所有正在运行的代理
                            foreach (var item in dgProxies.Items)
                            {
                                if (item is ProxyConfig config && config.IsEnabled)
                                {
                                    StopProxy(config);
                                }
                            }

                            // 清空现有配置
                            dgProxies.Items.Clear();

                            // 导入新配置
                            foreach (var config in configs)
                            {
                                dgProxies.Items.Add(new ProxyConfig
                                {
                                    Name = config.Name,
                                    ListenPort = config.ListenPort,
                                    TargetIP = config.TargetIP,
                                    TargetPort = config.TargetPort,
                                    IsEnabled = false,
                                    Status = "已停止"
                                });
                            }

                            MessageBox.Show("配置导入成功！", "成功", MessageBoxButton.OK, MessageBoxImage.Information);
                        }
                    }
                    else
                    {
                        MessageBox.Show("导入的配置文件格式不正确或为空。", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"导入配置失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
    }
}